package com.atguigu.shardingjdbcdemo.config;

import org.apache.shardingsphere.api.sharding.ShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.math.BigInteger;
import java.util.Collection;

/**
 * https://blog.csdn.net/qq_41712271/article/details/105630236
 * https://blog.csdn.net/qq_42402854/article/details/124225023
 *
 */
public class CustomHashShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        //实现按照 = 或 IN 进行精确分片。
        //例如 select * from course where id = 1 or id in (1,3,5)
        //实现course_$->{cid%2+1} 分表策略
        BigInteger shardingValueB = BigInteger.valueOf(shardingValue.getValue().hashCode());
        BigInteger resB = shardingValueB.mod(new BigInteger("2"))
                .add(new BigInteger("1"));
        String key =  shardingValue.getLogicTableName()+"_"+resB ;
        if(availableTargetNames.contains(key)){
            return key;
        }
        throw new UnsupportedOperationException(" route "+key+" is not supported. please check your config");
    }
}
